package com.example.study_backstage.utils;

import com.example.study_backstage.constant.CommonConstant;
import com.example.study_backstage.entity.SysUser;
import com.example.study_backstage.entity.dto.LoginUser;
import com.example.study_backstage.service.SysUserService;

/**
 * @author lxw
 * @version 1.0
 * @data 2023/3/29
 */
public class TokenUtils {

    /**
     * 获取登录用户
     *
     * @param sysUserService
     * @param username
     * @return
     */
    public static SysUser getLoginUser(String username, SysUserService sysUserService, RedisUtil redisUtil) {
        SysUser loginUser = null;
        String loginUserKey = CommonConstant.SYS_USERS_CACHE + "::" + username;
        //【重要】此处通过redis原生获取缓存用户，是为了解决微服务下system服务挂了，其他服务互调不通问题---
        if (redisUtil.hasKey(loginUserKey)) {
            loginUser = (SysUser) redisUtil.get(loginUserKey);
        } else {
            // 查询用户信息
            loginUser = sysUserService.getUser(username);
        }
        return loginUser;
    }

    /**
     * 验证token是否过期
     * @param token
     * @param redisUtil
     * @return
     */
    public static boolean jwtTokenRefresh(String token, RedisUtil redisUtil) {
        String cacheToken = (String) redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token);
        if (oConvertUtils.isNotEmpty(cacheToken)) return true;
        return false;
    }

    /**
     * 刷新token（保证用户在线操作不掉线）
     * @param token
     * @param userName
     * @param passWord
     * @param redisUtil
     * @return
     */
    public static boolean jwtTokenRefresh(String token, String userName, String passWord, RedisUtil redisUtil) {
        String cacheToken = redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token).toString();
        if (oConvertUtils.isNotEmpty(cacheToken)) {
            //校验token有效性
            if (!JwtUtil.verify(cacheToken, userName, passWord)) {
                //生成token
                String newAuthorization = JwtUtil.sign(userName, passWord);
                // 设置Toekn缓存有效时间-增加时间
                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
            }
            return true;
        }
        return false;
    }
}
